<?php





abstract class Log {

    private static $ops_id;
    private static $ops_name;



    private static function _init() {
        static $init;

        if (isset($init)) return $init;
        $init = false;

        $res = DB::query('SELECT * FROM `admin_operations`');
        if (!$res || !DB::state()) return $init;

        while($row = mysqli_fetch_array($res, MYSQLI_ASSOC)){
            $id =   Arr::getValue($row, 'id', FALSE);
            $name = Arr::getValue($row, 'name', FALSE);
            if ($id && $name) {
                self::$ops_id[$id]        = $row;
                self::$ops_name[$name]    = $row;
            }
        }
        $init = true;
        return $init;
    }


    public static function OpById($opId) {
        if (!self::_init()) return false;
        return Arr::getValue(self::$ops_id, $opId, false);
    }

    public static function OpByName($opName) {
        if (!self::_init()) return false;
        return Arr::getValue(self::$ops_name, $opName, false);
    }



    public static function Save($operation, $details) {
        if (!self::_init()) return false;

        $id = self::OpByName($operation);
        if (!$id) $id = self::OpById($operation);
        if ($id) $id = Arr::getValue($id, 'id', 0);

        if ($id<=0) return false;

        $d = @serialize($details);
        $itemid = Arr::getValue($details, 'id', '');

        $res = DB::query("INSERT INTO `admin_log` (`id`,`operation_id`,`item_id`,`details`) VALUES (NULL, $id, '$itemid', '$d')");
        //$err = DB::$mysqli->error;
        return $res && DB::state();
    }




    public static function getByOperation($ops) {
        $data = array();
        if (!self::_init()) return $data;

        if (!is_array($ops)) $ops = array($ops);
        $ids = array();

        foreach ($ops as $operation) {
            $id = self::OpByName($operation);
            if (!$id) $id = self::OpById($operation);
            if ($id>0) $ids[] = $id;
        }

        $ops = join(',',$ids);

        $res = DB::query("SELECT * FROM `admin_operations` WHERE `operation_id` IN ($ops)");
        if (!$res || !DB::state()) return $data;

        while($row = mysqli_fetch_array($res, MYSQLI_ASSOC)){
            $id =  Arr::getValue($row, 'id', FALSE);
            if ($id) $data[$id] = $row;
        }

        return $data;
    }

}
?>